package com.mongo.api;

import com.tanhua.dubbo.mongo.FriendAPI;
import com.tanhua.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@DubboService
public class FriendAPIImpl implements FriendAPI {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {
        //先判断一下，这对好友关系是否已经存在，如果不存在，则保存
        //添加好友是，互为好友
        //1 判断userId 的朋友有没有FirendId，没有就新增，有就不管
        Query query1 = new Query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        Friend friends1 = mongoTemplate.findOne(query1, Friend.class);
        if (friends1==null){
            Friend f1 = new Friend();
            f1.setUserId(userId);
            f1.setFriendId(friendId);
            f1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(f1);
        }
        //2 判断friendId的朋友有没有UserId，没有就新增，有就不管
        Query query2 = new Query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        Friend friends2 = mongoTemplate.findOne(query2, Friend.class);
        if (friends2==null){
            Friend f2 = new Friend();
            f2.setUserId(friendId);
            f2.setFriendId(userId);
            f2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(f2);
        }

    }

    @Override
    public List<Friend> findFirendList(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.find(query,Friend.class);
    }
}
